<template>
  <page-layout :avatar="currUser.avatar">
    <div slot="headerContent">
      <div class="title">
        {{ welcome.timeFix[lang] }}，{{ currUser.name }}!
        {{ welcome.message[lang] }}~
      </div>
      <div>让我们以代码敲击梦想~</div>
    </div>
    <!-- <template slot="extra">
      <head-info
        class="split-right"
        title="项目数"
        :content="projects.length"
      />
    </template> -->
    <template>
      <a-row style="margin: 0 -12px">
        <a-col
          style="padding: 0 12px"
          :xl="24"
          :lg="24"
          :md="24"
          :sm="24"
          :xs="24"
        >
          <a-card
            class="project-list"
            :loading="loading"
            style="margin-bottom: 24px"
            :bordered="false"
            title="我的项目"
            :body-style="{ padding: 0 }"
          >
            <!-- <a slot="extra" @click="showModal">新增项目</a> -->
            <div>
              <a-card-grid :key="item.id" v-for="item in projects">
                <a-card :bordered="false" :body-style="{ padding: 0 }">
                  <!-- <a-card-meta :description="item.desc"> -->
                  <a-card-meta>
                    <div slot="title" class="card-title">
                      <a-tag color="blue">项目:</a-tag>
                      <span>{{ item.name }},ID:{{ item.id }}</span>
                    </div>
                  </a-card-meta>
                  <!-- <div class="project-item" style="margin-top: 10px">
                    <a-tag color="cyan">设为默认:</a-tag>
                    <a-switch
                      checked-children="是"
                      un-checked-children="否"
                      :checked="defaultId == item.id"
                      @change="changeProject(item.id)"
                    />
                  </div> -->
                  <div class="project-item" style="margin-top: 10px">
                    <a-button size="small" type="primary" @click="edit(item)"
                      >编辑</a-button
                    >
                  </div>
                  <div
                    class="project-item"
                    style="
                  margin-top: 10px;"
                  >
                    <a :href="item.url" target="blank">快速访问</a>
                  </div>
                </a-card>
              </a-card-grid>
            </div>
          </a-card>
          <a-card :loading="loading" title="动态" :bordered="false">
            <a-list :pagination="pagination" :data-source="activities">
              <a-list-item slot="renderItem" key="item.id" slot-scope="item">
                <div>
                  <span>
                    <a-icon type="notification" />公告{{ item.id }}:
                  </span>
                  <em>{{ item.content }}</em>
                </div>
              </a-list-item>
            </a-list>
          </a-card>
        </a-col>
      </a-row>
      <a-modal
        v-model="visible"
        title="新增项目"
        ok-text="确认"
        cancel-text="取消"
        @ok="hideModal"
      >
        <a-form-model :model="form" ref="ruleForm">
          <a-form-model-item label="项目名称" prop="name">
            <a-input v-model="form.name" />
          </a-form-model-item>
          <a-form-model-item label="平台名称" prop="title">
            <a-input v-model="form.title" />
          </a-form-model-item>
          <a-form-model-item label="平台简介" prop="desc">
            <a-input v-model="form.desc" />
          </a-form-model-item>
          <a-form-model-item label="预览地址" prop="url">
            <a-input
              v-model="form.url"
              placeholder="请输入完整地址,https://或http://"
            />
          </a-form-model-item>
          <a-form-model-item label="平台LOGO" prop="logo">
            <AvatarUpload @setLogo="setLogo" ref="avatarCom"></AvatarUpload>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </template>
  </page-layout>
</template>

<script>
import PageLayout from '@/layouts/PageLayout';
import HeadInfo from '@/components/tool/HeadInfo';
import AvatarUpload from '@/components/tool/AvatarUpload';
import { userinfo } from '@/services/user';
import {
  projectsList,
  setProject,
  addProject,
  updateProject,
} from '@/services/project';
// import { getNoticesList } from '@/services/notice';
import { mapState, mapMutations } from 'vuex';

const timeList = [
  {
    CN: '早上好',
    HK: '早晨啊',
    US: 'Good morning',
  },
  {
    CN: '上午好',
    HK: '上午好',
    US: 'Good morning',
  },
  {
    CN: '中午好',
    HK: '中午好',
    US: 'Good afternoon',
  },
  {
    CN: '下午好',
    HK: '下午好',
    US: 'Good afternoon',
  },
  {
    CN: '晚上好',
    HK: '晚上好',
    US: 'Good evening',
  },
];
const welcomeMessages = [
  {
    CN: '休息一会儿吧!',
    HK: '休息一會兒吧',
    US: 'you may need a break',
  },
  {
    CN: '准备吃什么呢?',
    HK: '準備吃什麼呢',
    US: 'what are you going to eat',
  },
  {
    CN: '起来走走吧?',
    HK: '起来走走吧?',
    US: 'how about walking around',
  },
  {
    CN: '我猜你可能累了',
    HK: '我猜你可能累了',
    US: 'i guess you might be tired',
  },
];
export default {
  name: 'WorkPlace',
  components: { HeadInfo, PageLayout, AvatarUpload },
  i18n: require('./i18n'),
  data() {
    return {
      projects: [],
      loading: true,
      visible: false,
      defaultId: '',
      delVisible: false,
      imageUrl: '',
      form: {
        name: '',
        id: '',
        title: '',
        logo: '',
        desc: '',
      },

      // 当前操作行信息
      currentRecord: null,
      activities: [],
      teams: [],
      welcome: {
        timeFix: '',
        message: '',
      },
      pagination: {
        pageSize: 20,
      },
    };
  },
  computed: {
    ...mapState('account', { currUser: 'user' }),
    ...mapState('setting', ['lang', 'systemName', 'systemLogo']),
  },
  methods: {
    ...mapMutations('account', ['setUser', 'setPermissions', 'setRoles']),
    ...mapMutations('setting', ['setSystemName', 'setSystemLogo']),
    setLogo(imgSrc) {
      this.form.logo = imgSrc.path;
    },
    changeProject(id) {
      if (this.defaultId == id) {
        this.$message.warning('已经是默认项目了');
        return;
      }
      setProject({ id }).then((res) => {
        this.$message.success(res.msg);
        this.setUser(res.result);
        this.defaultId = res.result.project_id;
        sessionStorage.clear();

        let tempList = this.projects.filter((item) => {
          return item.id === this.defaultId;
        });

        // 设置平台名称
        if (tempList[0].title) {
          sessionStorage.setItem('title', tempList[0].title);
          this.setSystemName(tempList[0].title);
        }
        // 设置平台logo
        if (tempList[0].logo) {
          sessionStorage.setItem('logo', tempList[0].logo);
          this.setSystemLogo(tempList[0].logo);
        }
      });
    },
    timeFix() {
      const time = new Date();
      const hour = time.getHours();
      return hour < 9
        ? timeList[0]
        : hour <= 11
        ? timeList[1]
        : hour <= 13
        ? timeList[2]
        : hour <= 20
        ? timeList[3]
        : timeList[4];
    },
    msg() {
      const time = new Date();
      const hour = time.getHours();
      return hour < 9
        ? welcomeMessages[0]
        : hour <= 11
        ? welcomeMessages[1]
        : hour <= 13
        ? welcomeMessages[2]
        : hour <= 20
        ? welcomeMessages[3]
        : welcomeMessages[3];
    },
    checkedItem() {
      const defaultId =
        JSON.parse(localStorage.getItem('user')).project_id ||
        this.currUser.project_id;
      this.defaultId = defaultId;
    },
    showModal() {
      this.visible = true;
      this.form = {
        name: '',
        title: '',
        logo: '',
        desc: '',
        url: '',
      };
    },
    // 新增
    hideModal() {
      if (!this.form.name) {
        this.$message.error('请输入项目名称');
        return;
      }
      this.visible = false;
      // 编辑更新
      if (this.currentRecord) {
        updateProject(this.form)
          .then((res) => {
            this.$message.success(res.msg);
            this.getPojectList();

            // 设置平台名称
            if (res.result.title) {
              sessionStorage.setItem('title', res.result.title);
              this.setSystemName(res.result.title);
            }
            // 设置平台logo
            if (res.result.logo) {
              sessionStorage.setItem('logo', res.result.logo);
              this.setSystemLogo(res.result.logo);
            }
          })
          .catch((err) => {
            this.$message.error(err.msg);
          });
      }
      // 新增
      else {
        addProject(this.form)
          .then((res) => {
            this.$message.success(res.msg);
            this.getPojectList();
          })
          .catch((err) => {
            this.$message.error(err.msg);
          });
      }
      // 清空图片上传组件中的imgUrl
      this.$refs.avatarCom.imageUrl = '';
      this.currentRecord = null;
    },
    edit(item) {
      this.visible = true;

      // 打开编辑时，数据的来源
      this.form = {
        id: item.id,
        name: item.name,
        title: item.title || this.systemName,
        logo: item.logo || this.systemLogo,
        desc: item.desc,
        url: item.url,
      };
      this.currentRecord = item;
    },
    getPojectList() {
      this.loading = true;
      projectsList()
        .then((res) => {
          this.projects = res.result;
          sessionStorage.setItem('projectsList', JSON.stringify(res.result));
          this.loading = false;
        })
        .catch((err) => {
          this.$message.error(err.msg);
        });
    },
  },
  async created() {
    this.welcome.timeFix = this.timeFix();
    this.welcome.message = this.msg();

    // try {
    //   const notices = await getNoticesList();
    //   this.activities = notices.result;
    // } catch (error) {
    //   this.$message.error(error);
    // }

    if (!localStorage.getItem('user')) {
      try {
        const res = await userinfo();
        this.setUser(res.result);
        let role = {};
        if (res.result.type == 3) {
          role.id = 'admin';
        } else {
          role.id = 'user';
        }
        let rolesArr = [];
        rolesArr.push(role);
        this.setRoles(rolesArr);
      } catch (error) {
        this.$message.error(error);
      }
    }
    if (!sessionStorage.getItem('projectsList')) {
      let userData = JSON.parse(localStorage.getItem('user'));
      projectsList({ id: userData.id })
        .then((res) => {
          this.projects = res.result;
          let projectId = userData.project_id;
          this.projects.some((item) => {
            if (item.id == projectId) {
              // 设置平台名称
              if (item.title) {
                sessionStorage.setItem('title', item.title);
                this.setSystemName(item.title);
              }
              // 设置平台logo
              if (item.logo) {
                sessionStorage.setItem('logo', item.logo);
                this.setSystemLogo(item.logo);
              }
              return;
            }
          });
          sessionStorage.setItem('projectsList', JSON.stringify(res.result));
          this.loading = false;
        })
        .catch((err) => {
          this.$message.error(err.msg);
        });
    } else {
      this.projects = JSON.parse(sessionStorage.getItem('projectsList'));
    }
    this.checkedItem();
    this.loading = false;
  },
};
</script>

<style lang="less">
@import 'index';
</style>
